local ok, tree = pcall(require, 'nvim-tree')
if not ok then
  print('nvim-tree load error')
  return
end

vim.g.loaded = 1
vim.g.loaded_netrwPlugin = 1

tree.setup({
  sort_by = "case_sensitive",

  view = {
    adaptive_size = true,
    mappings = {
      list = {
        { key = "u", action = "dir_up" },
        { key = "v", action = "vsplit" },
        { key = "s", action = "split" },
      },
    },
  },

  renderer = {
    group_empty = true,
  },

  filters = {
    dotfiles = true,
  },
})

vim.api.nvim_set_keymap('n', '<leader>t', ':NvimTreeToggle<CR>', {noremap = true, silent = true})
vim.api.nvim_set_keymap('n', '<leader>l', ':NvimTreeFindFile<CR>', {noremap = true, silent = true})

-- try to close nvim when only NvimTree is open
vim.cmd([[autocmd BufEnter * if (winnr("$") == 1 && bufname('%') =~ 'NvimTree_\d') | q | endif]])
-- If another buffer tries to replace NvimTree, put it in the other window, and bring back NvimTree.
vim.cmd([[autocmd BufEnter * if bufname('#') =~ 'NvimTree_\d\+' && bufname('%') !~ 'NERD_tree_\d\+' && winnr('$') > 1 | let buf=bufnr() | buffer# | execute "normal! \<C-W>w" | execute 'buffer'.buf | endif]])

vim.cmd([[autocmd FileType NvimTree set laststatus=0 showtabline=0 | autocmd BufLeave <buffer> set laststatus=2 showtabline=2]])
